package com.demo.youxuanmall.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.Address;
import com.demo.youxuanmall.entity.Cart;
import com.demo.youxuanmall.entity.Order;
import com.demo.youxuanmall.entity.User;
import com.demo.youxuanmall.service.AddressService;
import com.demo.youxuanmall.service.CartService;
import com.demo.youxuanmall.service.OrderService;
import com.demo.youxuanmall.service.SystemSettingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController {

    private final OrderService orderService;
    private final CartService cartService;
    private final AddressService addressService;

    public OrderController(SystemSettingService systemSettingService,
                        OrderService orderService,
                        CartService cartService,
                        AddressService addressService) {
        super(systemSettingService);
        this.orderService = orderService;
        this.cartService = cartService;
        this.addressService = addressService;
    }

    /**
     * 订单确认页面
     */
    @GetMapping("/confirm")
    public String confirmOrder(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        // 获取购物车商品
        Result<List<Cart>> result = cartService.getUserCartItems(user.getId());
        List<Cart> cartItems = result.getData();
        if (cartItems == null || cartItems.isEmpty()) {
            return "redirect:/cart";
        }
        
        // 获取用户地址
        List<Address> addresses = addressService.getUserAddresses(user.getId());
        
        // 计算总价
        BigDecimal totalAmount = cartItems.stream()
                .map(item -> item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        model.addAttribute("cartList", cartItems);
        model.addAttribute("addressList", addresses);
        model.addAttribute("totalAmount", totalAmount);
        
        return "order/checkout";
    }
    
    /**
     * 提交订单
     */
    @PostMapping("/submit")
    @ResponseBody
    public Result<Order> submitOrder(@RequestBody Map<String, Object> orderInfo, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        
        Long addressId = Long.parseLong(orderInfo.get("addressId").toString());
        
        return orderService.createOrder(user.getId(), addressId);
    }
    
    /**
     * 订单详情
     */
    @GetMapping("/detail/{id}")
    public String orderDetail(@PathVariable("id") Long orderId, Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        // 将Long转为String，适配接口
        String orderNo = orderId.toString();
        Result<Order> result = orderService.getOrderDetail(user.getId(), orderNo);
        
        if (result.getCode() != 0 || result.getData() == null) {
            return "redirect:/404";
        }
        
        model.addAttribute("order", result.getData());
        return "order/detail";
    }
    
    /**
     * 支付订单页面
     */
    @GetMapping("/pay/{id}")
    public String payOrder(@PathVariable("id") String orderNo, Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        Result<Order> result = orderService.getOrderDetail(user.getId(), orderNo);
        
        if (result.getCode() != 0 || result.getData() == null || result.getData().getStatus() != 10) {
            return "redirect:/user/orders";
        }
        
        model.addAttribute("order", result.getData());
        return "order/pay";
    }
    
    /**
     * 完成支付
     */
    @PostMapping("/pay/{id}")
    @ResponseBody
    public Result<Void> completePay(@PathVariable("id") Long orderId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        
        // 将Long转为String，适配接口
        String orderNo = orderId.toString();
        return orderService.payOrder(user.getId(), orderNo);
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/cancel/{id}")
    @ResponseBody
    public Result<Void> cancelOrder(@PathVariable("id") Long orderId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        
        // 将Long转为String，适配接口
        String orderNo = orderId.toString();
        return orderService.cancelOrder(user.getId(), orderNo);
    }
    
    /**
     * 确认收货
     */
    @PostMapping("/confirm/{id}")
    @ResponseBody
    public Result<Void> confirmReceipt(@PathVariable("id") Long orderId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        
        // 将Long转为String，适配接口
        String orderNo = orderId.toString();
        return orderService.confirmOrder(user.getId(), orderNo);
    }
    
    /**
     * 我的订单页面
     */
    @GetMapping("/list")
    public String list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer status,
            HttpSession session,
            Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        try {
            Result<Page<Order>> result;
            if (status != null) {
                result = orderService.listUserOrdersByStatus(user.getId(), status, pageNum, pageSize);
            } else {
                result = orderService.listUserOrders(user.getId(), pageNum, pageSize);
            }
            
            if (result.getCode() == 0 && result.getData() != null) {
                model.addAttribute("orderPage", result.getData());
                model.addAttribute("status", status);
            } else {
                model.addAttribute("error", result.getMsg());
            }
            
            return "order/list";
        } catch (Exception e) {
            log.error("订单列表页加载异常", e);
            model.addAttribute("error", "加载订单列表失败，请稍后再试");
            return "order/list";
        }
    }

    /**
     * 订单结算页面
     */
    @GetMapping("/checkout")
    public String checkout(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        // 获取购物车商品
        Result<List<Cart>> result = cartService.getUserCartItems(user.getId());
        List<Cart> cartItems = result.getData();
        if (cartItems == null || cartItems.isEmpty()) {
            return "redirect:/cart";
        }
        
        // 获取用户地址
        List<Address> addresses = addressService.getUserAddresses(user.getId());
        
        // 计算总价
        BigDecimal totalAmount = cartItems.stream()
                .map(item -> item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        model.addAttribute("cartList", cartItems);
        model.addAttribute("addressList", addresses);
        model.addAttribute("totalAmount", totalAmount);
        
        return "order/checkout";
    }

    /**
     * 直接购买创建订单
     */
    @PostMapping("/create")
    @ResponseBody
    public Result<Order> createOrder(@RequestBody Map<String, Object> orderInfo, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        
        Integer productId = (Integer) orderInfo.get("productId");
        Integer quantity = (Integer) orderInfo.get("quantity");
        
        if (productId == null || quantity == null) {
            return Result.error("参数错误");
        }
        
        return orderService.createOrderFromProduct(user.getId(), productId.longValue(), quantity);
    }
}